//
//  BarCodeViewController.m
//  WeiBao
//
//  Created by macbook on 16/5/12.
//  Copyright © 2016年 ucox. All rights reserved.
//

#import "BarCodeViewController.h"
#import "ZBarSDK.h"
#import "ZBarReaderView.h"
#import "BarCodeView.h"
#import "BarCodeDetailsViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface BarCodeViewController ()<ZBarReaderViewDelegate>
{
    ZBarReaderView *zbarReadView;
    ZBarImageScanner *scanner1;
    BarCodeView *_barCodeView;
    UIView *_QrCodeline;
    NSTimer *_timer;
    NSString *dataString;
    
}

@property (nonatomic,strong) AVCaptureSession * captureSession;
@property (nonatomic,strong) AVCaptureDevice * captureDevice;

@property(nonatomic,retain)AVCaptureSession * AVSession;
@end

@implementation BarCodeViewController


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    // 禁用 iOS7 返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    // 开启
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    }
    [zbarReadView stop];
    [_timer invalidate];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [zbarReadView start];
    [self createTimer];
    [_timer fire];
}

- (void)viewDidLoad
{
    [super hideNaviBar:YES];
    [super viewDidLoad];
    
    self.title = @"二维码/条形码扫描";
    
    [self addZBarView];
    [self addControlButton];

}
- (void)addZBarView
{
    zbarReadView=[[ZBarReaderView alloc]init];
    
    zbarReadView.frame=CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        
    zbarReadView.tracksSymbols = NO ;
    
    zbarReadView.readerDelegate=self;
    
    zbarReadView.scanCrop = CGRectMake(KLeftSpace, (ScreenHeight-(ScreenWidth-2*KLeftSpace))/2, ScreenWidth-2*KLeftSpace, ScreenWidth-2*KLeftSpace);
    
     scanner1 = zbarReadView.scanner;
    
    [scanner1 setSymbology:ZBAR_I25 config:ZBAR_CFG_ENABLE to:0];
    
    _barCodeView=[[BarCodeView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    
    [zbarReadView addSubview:_barCodeView];
    
    zbarReadView.scanCrop=[self getScanCrop:zbarReadView.frame readerViewBounds:_barCodeView.middleView.frame];
    
    [self.view insertSubview:zbarReadView atIndex:0];
    
    _QrCodeline = [[ UIView alloc ] initWithFrame : CGRectMake (KLeftSpace , (ScreenHeight-(ScreenWidth-2*KLeftSpace))/2 ,ScreenWidth-2*KLeftSpace , 2 )];
    
    _QrCodeline.backgroundColor = [ UIColor greenColor];
    
    [zbarReadView addSubview : _QrCodeline];
}

-(CGRect)getScanCrop:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds
{
    CGFloat x,y,width,height;
    
    x = rect.origin.x / readerViewBounds.size.width;
    y = rect.origin.y / readerViewBounds.size.height;
    width = rect.size.width / readerViewBounds.size.width;
    height = rect.size.height / readerViewBounds.size.height;
    
    return CGRectMake(x, y, width, height);
}



-(void)addControlButton
{
    
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(0, 40, 50, 30)];
        
        [button addTarget:self action:@selector(controlButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    button.tag=312;
        [button setTitle:@"取消" forState:UIControlStateNormal];

        [zbarReadView addSubview:button];
    
    UIButton *button1 = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth-50, 40, 50, 30)];
    
    [button1 addTarget:self action:@selector(controlButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    button1.tag=314;
    [button1 setTitle:@"闪光" forState:UIControlStateNormal];
    
    [zbarReadView addSubview:button1];
  
}

- (void)controlButtonClick:(UIButton *)button
{
    zbarReadView.torchMode = 4;
    if (button.tag==312) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        
        AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
     
        AVCaptureSession * session = [[AVCaptureSession alloc]init];

        if (device.torchMode==AVCaptureTorchModeOff||device.torchMode==2) {
             NSLog(@"闪光灯");
            AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
            [session addInput:input];

            [device setTorchMode:AVCaptureTorchModeOn];

            [session startRunning];
        }else{
            NSLog(@"关闭闪光灯");
            AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
            [session addInput:input];
            
            [device setTorchMode:AVCaptureTorchModeOff];
            [session stopRunning];
        
        }
    }
}



- (void)createTimer
{
    //创建一个时间计数
    _timer=[NSTimer scheduledTimerWithTimeInterval: 1.5 target: self selector: @selector(moveUpAndDownLine) userInfo: nil repeats: YES ];
}

//二维码的横线移动
- ( void )moveUpAndDownLine
{
    CGFloat Y= _QrCodeline . frame . origin . y ;
    if ((ScreenHeight-(ScreenWidth-2*KLeftSpace))/2==Y)
    {
        [UIView beginAnimations: @"asa" context: nil ];
        [UIView setAnimationDuration: 1.5 ];
        _QrCodeline.frame=CGRectMake(KLeftSpace,(ScreenHeight-(ScreenWidth-2*KLeftSpace))/2 + ScreenWidth-2*KLeftSpace , ScreenWidth-2*KLeftSpace, 1 );
        [UIView commitAnimations];
    }
    else if
        ((ScreenHeight-(ScreenWidth-2*KLeftSpace))/2 + ScreenWidth-2*KLeftSpace ==Y)
    {
        _QrCodeline.frame = CGRectMake (KLeftSpace , (ScreenHeight-(ScreenWidth-2*KLeftSpace))/2 ,ScreenWidth-2*KLeftSpace , 1 );
        
        [self moveUpAndDownLine];
        
        }
}


- (void) readerView: (ZBarReaderView*) readerView
     didReadSymbols: (ZBarSymbolSet*) symbols
          fromImage: (UIImage*) image
{
    for (ZBarSymbol *symbol in symbols)
    {
        //处理部分中文乱码问题
        
        dataString = symbol.data;
        
        if ([dataString canBeConvertedToEncoding:NSShiftJISStringEncoding])
        {
            dataString = [NSString stringWithCString:[dataString cStringUsingEncoding: NSShiftJISStringEncoding] encoding:NSUTF8StringEncoding];
        }
        
        if (self.returnTextBlock != nil) {
            if (dataString) {
                self.returnTextBlock(dataString);
            }
        }

        [self.navigationController popViewControllerAnimated:YES];

        
    }
}

-(void)pushToNextViewControllerWithData:(NSString *)string WithImage:(UIImage *)image
{
    BarCodeDetailsViewController *barCodeDetails = [[BarCodeDetailsViewController alloc]init];
    
    barCodeDetails.dataString = string;
    
    barCodeDetails.codeImage = image;
    
    [self.navigationController pushViewController:barCodeDetails animated:YES];
}
/**
 * 截取部分图像
 *
 **/

-(UIImage*)getSubImage:(UIImage *)image mCGRect:(CGRect)mCGRect centerBool:(BOOL)centerBool
{
    
    /*如若centerBool为Yes则是由中心点取mCGRect范围的图片*/
    
    
    float imgwidth = image.size.width;
    float imgheight = image.size.height;
    float viewwidth = mCGRect.size.width;
    float viewheight = mCGRect.size.height;
    CGRect rect;
    if(centerBool)
        rect = CGRectMake((imgwidth-viewwidth)/2, (imgheight-viewheight)/2, viewwidth, viewheight);
    else{
        if (viewheight < viewwidth) {
            if (imgwidth <= imgheight) {
                rect = CGRectMake(0, 0, imgwidth, imgwidth*viewheight/viewwidth);
            }else {
                float width = viewwidth*imgheight/viewheight;
                float x = (imgwidth - width)/2 ;
                if (x > 0) {
                    rect = CGRectMake(x, 0, width, imgheight);
                }else {
                    rect = CGRectMake(0, 0, imgwidth, imgwidth*viewheight/viewwidth);
                }
            }
        }else {
            if (imgwidth <= imgheight) {
                float height = viewheight*imgwidth/viewwidth;
                if (height < imgheight) {
                    rect = CGRectMake(0, 0, imgwidth, height);
                }else {
                    rect = CGRectMake(0, 0, viewwidth*imgheight/viewheight, imgheight);
                }
            }else {
                float width = viewwidth*imgheight/viewheight;
                if (width < imgwidth) {
                    float x = (imgwidth - width)/2 ;
                    rect = CGRectMake(x, 0, width, imgheight);
                }else {
                    rect = CGRectMake(0, 0, imgwidth, imgheight);
                }
            }
        }
    }
    
    CGImageRef subImageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
    CGRect smallBounds = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
    
    UIGraphicsBeginImageContext(smallBounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextDrawImage(context, smallBounds, subImageRef);
    UIImage* smallImage = [UIImage imageWithCGImage:subImageRef];
    UIGraphicsEndImageContext();
    
    return smallImage;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    
    return NO;
}
-(BOOL)hidesBottomBarWhenPushed{
    
    return YES;
}
- (void)returnText:(ReturnSendOrddata)block {
    
    self.returnTextBlock = block;
    
}


@end
